<template>
  <div class="page-content" :style="{height:minHeight}">
    <div class="left-group">
      <el-button @click="showGroupDialog('add')">添加分组</el-button>
      <div class="warp">
        <ul>
          <li class="item" :class="group_id === item.id ? 'ac' : ''" v-for="item in groupData" :key="item.id" @click="chooseGroup(item)">
            <span>{{item.name}}</span>
            <div>
              <el-button size="small" text plain @click="showGroupDialog('edit',item)">编辑</el-button>
              <el-button size="small" text plain @click="delGroup(item)">删除</el-button>
              <el-button size="small" text plain @click="bindXhsAccount(item)">绑定账号</el-button>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="right-container" style="height: 100%">
      <table-bar
        :showTop="false"
        @search="search"
        @reset="resetForm(searchFormRef)"
        layout="search refresh"
      >
<!--        <template #bottom>-->
<!--          <el-button @click="bindXhsAccount" v-ripple>绑定账号</el-button>-->
<!--        </template>-->
      </table-bar>
      <art-table style="margin-top: 0" :data="accountList" show-header-background>
        <template #default>
          <el-table-column label="授权账号" prop="name" />
          <el-table-column label="是否授权" prop="auth_status" #default="{row}">
            <el-tag v-if="row.auth_status === 1">是</el-tag>
            <el-tag v-else>否</el-tag>
          </el-table-column>
          <el-table-column label="是否绑定" prop="bind_status" #default="{row}">
            <el-tag v-if="row.bind_status === 1">是</el-tag>
            <el-tag v-else>否</el-tag>
          </el-table-column>
          <el-table-column label="可用状态" prop="status" #default="{row}">
            <el-tag v-if="row.status === 1">可用</el-tag>
            <el-tag v-else>不可用</el-tag>
          </el-table-column>
          <el-table-column label="创建日期" prop="create_time" sortable />
          <el-table-column fixed="right" label="操作" width="150px">
            <template #default="scope">
              <button-table type="delete" @click="deleteAccount(scope.row)" />
              <button-table type="more" @click="showMaterialDialog(scope.row)" />
            </template>
          </el-table-column>
        </template>
      </art-table>
    </div>
    <!--  添加分组-->
    <el-dialog
      v-model="dialogGroupVisible"
      :title="dialogGroupType === 'add' ? '添加分组' : '编辑分组'"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input type="textarea" v-model="formData.remark" :autosize="{ minRows: 2, maxRows: 6 }"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogGroupVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物料弹窗 -->
    <el-dialog v-model="dialogMaterialVisible" title="物料列表" width="40%">

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules,FormInstance } from 'element-plus'
  import {AccountService,GroupService} from '@/api/accountGroup/accountGroup'
  import {MaterialService} from '@/api/user/materialApi'
  import { getUrlParam } from '@/utils/utils'
  import { useSettingStore } from '@/store/modules/setting'

  const settingStore = useSettingStore()
  const showWorkTab = computed(() => settingStore.showWorkTab)
  const minHeight = computed(() => `calc(100vh - ${showWorkTab.value ? 120 : 75}px)`)
  const formData = reactive({
    name: '',
    remark: '',
    setting: '',
    sort: ''
  })

  // 物料弹窗
  const dialogMaterialVisible = ref(false)

  // 分组账号dialog
  const dialogGroupVisible = ref(false)
  const dialogGroupType = ref('add')

  // 绑定账号dialog
  const dialogVisible = ref(false)
  const dialogType = ref('add')

  const groupTotal = ref(0)
  const groupData = ref()
  // 分组id
  const group_id = ref(0)

  const query = {
    group_id:'',
    type:'',
    third_id:'',//第三方账号ID
    status:'',//0 离线 1 正常
  }
  let auth_code = ''

  // 是否点击绑定按钮
  let isBindTag = JSON.parse(localStorage.getItem('isBindTag')) || false
  console.log('isBindTag',isBindTag)

  if(isBindTag) {
    initAuth()
  }
  // 初始化账号授权
  async function initAuth() {
    const path = location.href
    auth_code = getUrlParam(path,'auth_code')
    group_id.value = getUrlParam(path,'group_id')
    console.log('auth_code',auth_code)

    if(auth_code) {
      try {
        await AccountService.getCallbackAuth({auth_code,group_id:group_id.value})
        const res = await AccountService.getBindUrl(group_id.value)
        window.open(res.data,'_blank')
      } catch (err) {
        console.error(JSON.stringify(err))
      } finally {
        localStorage.setItem('isBindTag',JSON.stringify(false))
      }
    }
  }

  // 显示物料弹窗
  const showMaterialDialog = async (row:any)=> {
    dialogMaterialVisible.value = true
    // const res = await MaterialService.getMaterialPage({account_id:row.id,type:"trade_card"})
    const res = await MaterialService.materialSync({account_id:row.id,type:"social_card"})
    console.log('res',res)
  }

  getGroupPage().then(() => {
    getAccountPage()
  })
  // 获取分组列表
  async function getGroupPage() {
    const res = await GroupService.getGroupPage()
    groupData.value = res.data.list
    query.group_id = res.data.list[0].id
    group_id.value = res.data.list[0].id
    groupTotal.value = res.data.total
  }

  const accountList = ref([])

  // 获取账号列表
  async function getAccountPage() {
    const res = await AccountService.getPage(query)
    accountList.value = res.data.list
  }

  const searchFormRef = ref<FormInstance>()

  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }

  // 选择分组
  const chooseGroup = (row:any)=> {
    console.log('row',row.id)
    query.group_id = row.id
    group_id.value = row.id
    getAccountPage()
  }
  // 删除分组
  const delGroup = (row:any)=> {
    ElMessageBox.confirm('确定要删除该分组吗？', '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      await GroupService.groupDelete({id:row.id})
      await getGroupPage()
      ElMessage.success('删除成功')
    })
  }
  // 显示分组dialog
  const showGroupDialog = (type: string, row?: any)=> {
    dialogGroupVisible.value = true
    dialogGroupType.value = type

    if (type === 'edit' && row) {
      formData.name = row.name
      formData.remark = row.remark
    } else {
      formData.name = ''
      formData.remark = ''
    }
  }
  const tableData = reactive([])

  // 绑定小红书账号
  const bindXhsAccount = async (row:any)=> {
    const path = location.origin + location.pathname
    const res:any = await AccountService.getAuthUrl({callbackUrl:path,group_id:row.id})
    group_id.value = row.id
    setTimeout(() => {
      localStorage.setItem('isBindTag',JSON.stringify(true))
      location.href = res.data
    },300)
  }

  // 绑定账号弹窗
  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    if (type === 'edit' && row) {
      formData.name = row.name
      formData.remark = row.remark
    } else {
      formData.name = ''
      formData.remark = ''
    }
  }

  const buttonMoreClick = (type:string,row:any)=> {
    if(type === 'add') {

    }
  }

  // 删除账号
  const deleteAccount = (row:any) => {
    ElMessageBox.confirm('确定要删除该账号吗？', '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      await AccountService.delAccount({id:row.id})
      ElMessage.success('删除成功')
    })
  }

  const search = () => {}

  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入', trigger: 'blur' },
    ]
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async(valid) => {
      if (valid) {
        if(dialogGroupType.value === 'add') {
          await GroupService.groupCreate(formData)
        } else {
          await GroupService.groupUpdate(formData)
        }
        await getGroupPage()
        ElMessage.success(dialogGroupType.value === 'add' ? '添加成功' : '更新成功')
        dialogGroupVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    display: flex;
    .left-group {
      width: 20%;
      .warp {
        height: calc(100% - 40px);
        overflow-y: scroll;
        margin-top: 20px;
        .item {
          font-size: 14px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          cursor: pointer;
          .el-button {
            margin: 0;
            padding: 5px;
          }
        }
        .ac {
          background: #F6F6F6;
        }
        li {
          padding: 6px 16px;
          margin-bottom: 4px;
        }
      }
    }
    .right-container {
      width: 80%;
      margin-left: 4px;
    }
  }
</style>
